package priv.wangy.micro.common.po.valid.validator;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.util.StringUtils;
import priv.wangy.micro.common.po.valid.DigitString;

import java.util.regex.Pattern;

/**
 * @author zhangjq
 * @since 2024-07-03
 */
public class DigitStringValidator implements ConstraintValidator<DigitString, String> {

    private int min;

    private int max;

    private static final Pattern DIGIT = Pattern.compile("^[0-9]+$");

    @Override
    public void initialize(DigitString constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        min = constraintAnnotation.min();
        max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.hasLength(s)) {
            if (min > 0 && s.length() < min) {
                return false;
            }
            if (max > 0 && s.length() > max) {
                return false;
            }
            return DIGIT.matcher(s).matches();
        }
        return min == 0;
    }
}
